package com.ecms.webSetting.utils;

import cn.hutool.extra.template.*;
import cn.hutool.json.JSONUtil;
import me.zhengjie.utils.FileUtil;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

public class TemplateUtils {
    public static final String SYS_TEM_DIR = System.getProperty("java.io.tmpdir") + File.separator;

    public static void main(String[] args) {
        try {
            System.out.println(realFtlData("{\"a\":\"v\"}", "/home001/", "index111.html"));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 向模板传入数据
     *
     * @param resources 模板数据
     * @param filePath  文件路径
     * @param fileNmae  文件名称
     * @return
     * @throws IOException
     */
    public static String realFtlData(Object resources, String filePath, String fileNmae) throws IOException {


//        Map<String, Object> dataMap = JSONUtil.toBean(s, HashMap.class);

        Map<String,Object> dataMap = JSONUtil.toBean(JSONUtil.toJsonStr(resources), HashMap.class);
        String tempPath = (filePath.isEmpty() ? SYS_TEM_DIR : filePath) + fileNmae;
        TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH));
        Template template = engine.getTemplate("html/index.ftl");

        File file = new File(tempPath);
        genFile(file, template, dataMap);
//        dataMap.put("fileName",fileNameTemp);
//        FileUtil.downloadFile(request, response, new File(filePath), true);
        return tempPath;

    }

    private static void genFile(File file, Template template, Map<String, Object> map) throws IOException {
        // 生成目标文件
        Writer writer = null;
        try {
            FileUtil.touch(file);
            writer = new FileWriter(file);

            template.render(map, writer);
        } catch (TemplateException | IOException e) {
            throw new RuntimeException(e);
        } finally {
            assert writer != null;
            writer.close();
        }
    }
}
